package com.kye.express.business.president_online;

import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.kye.base.Logger;
import com.kye.express.BuildConfig;
import com.kye.express.R;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.LifecycleOpenApiResultObserver;
import com.kye.express.contract.base.view.RxView;
import com.kye.express.utils.Base64FileUtils;
import com.kye.express.utils.ImageUtils;
import com.kye.express.utils.StringUtils;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.president_online.PresidentOnlineAddResultBean;
import com.kye.model.bean.president_online.PresidentOnlineImagesModel;
import com.kye.model.bean.president_online.PresidentOnlineListBean;
import com.kye.model.bean.president_online.PresidentOnlineResBean;
import com.kye.model.bean.president_online.RequestPresidentOnlineAddBean;
import com.kye.model.bean.president_online.RequestPresidentOnlineListBean;
import com.kye.model.bean.president_online.RequestPresidentOnlineResBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.kye.model.gson_adapter.ApiException;
import com.kye.model.service.PresidentOnlineService;
import com.kye.model.service.UserService;
import com.oxbix.spanlogistics.utils.FileUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public interface PresidentOnlineAddFragmentContract {

    interface PresidentOnlineAddView extends RxView {

        void onComplete();

        void onLoading();

        void onLoaded(PresidentOnlineAddResultBean datas);

        void onError(String msg);

        void onUser(User user);

        void onCompleteRes();

        void onLoadingRes();

        void onLoadedRes(PresidentOnlineResBean presidentOnlineResBean);

        void onErrorRes(String msg);

    }

    class PresidentOnlineAddViewPresenter extends BasePresenter<PresidentOnlineAddFragmentContract.PresidentOnlineAddView> {

        private Context mContext;

        public PresidentOnlineAddViewPresenter(Context context) {
            this.mContext = context;
        }

        public void onUser() {
            UserSession.getInstance()
                    .getUserForRx()
                    .compose(getView().getProvider().<User>bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            getView().onUser(user);
                        }
                    });
        }

        /**
         * 请求服务器数据
         */
        public void loadDatas(RequestPresidentOnlineAddBean requestBean,List<PresidentOnlineImagesModel> imagesModels) {
            getView().onLoading();

            //base64 录音
            Observable<RequestPresidentOnlineAddBean> requestPresidentOnlineAddBeanObservable = Observable.just(requestBean)
                    .observeOn(Schedulers.io())
                    .doOnNext(new Consumer<RequestPresidentOnlineAddBean>() {
                        @Override
                        public void accept(RequestPresidentOnlineAddBean requestPresidentOnlineAddBean) throws Exception {
                            if (!TextUtils.isEmpty(requestPresidentOnlineAddBean.getAudio())) {
                                String audioFilePath = requestPresidentOnlineAddBean.getAudio();
                                String audioBase64 = Base64FileUtils.fileToBase64String(audioFilePath);
//                                StringUtils.saveLogToFile(audioBase64);
                                requestPresidentOnlineAddBean.setAudio(audioBase64);
                            }
                            return;
                        }
                    });
            //base64 图片
            Observable<RequestPresidentOnlineAddBean> requestPresidentOnlineAddBeanObservable1 = Observable.just(requestBean)
                    .observeOn(Schedulers.io())
                    .doOnNext(new Consumer<RequestPresidentOnlineAddBean>() {
                        @Override
                        public void accept(RequestPresidentOnlineAddBean requestPresidentOnlineAddBean) throws Exception {
                            if (TextUtils.isEmpty(requestPresidentOnlineAddBean.getCode()) && imagesModels != null && imagesModels.size() > 0) {
                                List<String> pictureBase64List = new ArrayList<String>();
                                for (int i = 0; i < imagesModels.size(); i++) {
                                    Bitmap bitmap = ImageUtils.getBitmap(imagesModels.get(i).getUrl());
                                    String base64 = ImageUtils.bitmaptoString(bitmap);
                                    pictureBase64List.add(base64);
                                    ImageUtils.recycleBitmap(bitmap);
                                }
                                requestPresidentOnlineAddBean.setPicture(pictureBase64List);
                            }
                            return;
                        }
                    });
            Observable.zip(requestPresidentOnlineAddBeanObservable1, requestPresidentOnlineAddBeanObservable, new BiFunction<RequestPresidentOnlineAddBean, RequestPresidentOnlineAddBean, RequestPresidentOnlineAddBean>() {
                @Override
                public RequestPresidentOnlineAddBean apply(RequestPresidentOnlineAddBean requestPresidentOnlineAddBean, RequestPresidentOnlineAddBean requestPresidentOnlineAddBean2) throws Exception {
                    return requestPresidentOnlineAddBean;
                }
            }).flatMap(new Function<RequestPresidentOnlineAddBean, ObservableSource<OpenApiResult<PresidentOnlineAddResultBean>>>() {
                @Override
                public ObservableSource<OpenApiResult<PresidentOnlineAddResultBean>> apply(RequestPresidentOnlineAddBean requestPresidentOnlineAddBean) throws Exception {
                    String phone = "";
                    User user = UserSession.getInstance().getUser();
                    if (user != null) {
                        phone = user.getPhone();
                    }
                    requestPresidentOnlineAddBean.setPhone(phone);
                    Logger.d(requestPresidentOnlineAddBean.toString());
                    return RetrofitManager.getInstance()
                            .createOpenApiService(PresidentOnlineService.class)
                            .addMessage(requestPresidentOnlineAddBean);
                }
            })
                    .compose(getView().<OpenApiResult<PresidentOnlineAddResultBean>>bindToLifecycleDestroy())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<OpenApiResult<PresidentOnlineAddResultBean>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(OpenApiResult<PresidentOnlineAddResultBean> presidentOnlineAddResultBeanOpenApiResult) {
                            if (presidentOnlineAddResultBeanOpenApiResult != null && presidentOnlineAddResultBeanOpenApiResult.isSuccess()) {
                                getView().onLoaded(presidentOnlineAddResultBeanOpenApiResult.getData());
                            } else {
                                getView().onError(mContext.getString(R.string.common_net_error));
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            if (e instanceof ApiException) {
                                if (!TextUtils.isEmpty(((ApiException) e).getOpenApiResult().getMsg())) {
                                    getView().onError(((ApiException) e).getOpenApiResult().getMsg());
                                } else {
                                    getView().onError(mContext.getString(R.string.common_net_error));
                                }
                            } else {
                                getView().onError(mContext.getString(R.string.common_net_error));
                            }
                        }

                        @Override
                        public void onComplete() {
                            if (getView() != null){
                                getView().onComplete();
                            }
                        }
                    });
        }

        public void loadResDatas(String guid, String type) {
            String phone = "";
            User user = UserSession.getInstance().getUser();
            if (user != null) {
                phone = user.getPhone();
            }

            RetrofitManager.getInstance().createOpenApiService(PresidentOnlineService.class)
                    .getResDatas(new RequestPresidentOnlineResBean(phone, guid, type))
                    .compose(getView().<OpenApiResult<PresidentOnlineResBean>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<PresidentOnlineResBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            //getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onErrorRes(mContext.getString(R.string.common_net_error));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onCompleteRes();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<PresidentOnlineResBean> result, PresidentOnlineResBean datas) {
                            if (datas != null) {
                                getView().onLoadedRes(datas);
                            } else {
                                getView().onErrorRes(mContext.getString(R.string.common_no_more_datas));
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<PresidentOnlineResBean> result, int code, String msg) {
                            if (!TextUtils.isEmpty(msg)) {
                                getView().onErrorRes(msg);
                            } else {
                                getView().onErrorRes(mContext.getString(R.string.common_net_error));
                            }
                        }
                    });
        }
    }
}
